//
//  PlaceOrderViewController.m
//  HAODE
//
//  Created by LiYinDi on 16/1/11.
//  Copyright © 2016年 reabam.com. All rights reserved.
//

#import "PlaceOrderViewController.h"
#import "PlaceOrderProductListViewController.h"
#import "RDVTabBarController.h"
#import "HttpRequest.h"
#import "TheLoginViewController.h"
//#import "SelectedGoodsViewController.h"
#import "SelectedGoodNewViewController.h"
#import "BusinessOrderExtAddViewController.h"
#import "BusinessWhsInAddViewController.h"
#import "HAODEsingleton.h"

#import "BusinessNeedOrderAddViewController.h"
#import "BusinessCheckVouchAddViewController.h"
#import "BusinessPOrderAddViewController.h"
#import "BusinessCheckVouchContinueViewController.h"
#import "ProductDetailViewController.h"
#import "ScanViewController.h"
#import "FMDB.h"
//>>>>>>>???
@interface PlaceOrderViewController ()<PlaceOrderProductListDelegate>
{
    UITextField *searchTextField;
    NSMutableArray *totalDataArray;
    NSMutableArray *parentTypeArray;
    NSString *userToken;
    
    HAODEsingleton*commdity;
    NSMutableArray *labelArray;
}
@property(nonatomic,strong)FMDatabase *userDB;
@end

@implementation PlaceOrderViewController
@synthesize alt = alt;
-(void)viewWillAppear:(BOOL)animated
{
    //     NSLog(@"self.Whs%@",self.Whs);
    // [ self resetDefaults];
    [self setNavigation];
//    userToken=@"";
    [super viewDidLoad];
    [self initDataBase];

    
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
   userToken = [user objectForKey:@"tokenId"];
   
   
    parentTypeArray=[NSMutableArray array];
    labelArray=[NSMutableArray array];
    [self requestProductType];
    commdity=[HAODEsingleton shared];
    commdity.userName=nil;
    commdity.status=nil;
    self.dataSource = self;
    self.delegate = self;


}
-(void)initDataBase
{
    NSString *dbPath = [self getDBPath];
    _userDB = [FMDatabase databaseWithPath:dbPath];
    if (![_userDB open]) {
        NSLog(@"open membersDB failed");
        return;
    }
    
}
-(NSString *)getDBPath
{
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *DBPath = [documentPath stringByAppendingPathComponent:kUserDBNAME];
    return DBPath;
}

-(void)requestProductType
{
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:userToken forKey:@"tokenId"];
    
    [Global showIndeterminateHud:@"加载中，请稍后。。。" delay:30 view:self.view];
    
    [HttpRequest requestData:@"Business/Order/ProductTypes" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                //               NSLog(@"severdata11===%@",severDataDict.dataDict);
                totalDataArray=[NSMutableArray arrayWithArray:[severDataDict.dataDict objectForKey:@"DataLine"]];
                
                
                for (int i=0;i<totalDataArray.count;i++)
                {
                    [parentTypeArray addObject:[[totalDataArray objectAtIndex: i] valueForKey:@"ParentName"]];
                    
                }
                NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                [userDefaults setObject:parentTypeArray forKey:@"parentTypeName"];
                [[NSUserDefaults standardUserDefaults] synchronize];
                [self reloadData];
                
            }else{
                [Global hideProgressHUDInternal:self.view];
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    
                    
//                    TheLoginViewController *detailViewController = [[TheLoginViewController alloc] init];
//                    [self.navigationController pushViewController:detailViewController animated:YES];
                }
                
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
        
    }];
    
    
}
#pragma mark - ViewPagerDataSource
- (NSUInteger)numberOfTabsForViewPager:(ViewPagerController *)viewPager {
    
    if (parentTypeArray.count>0) {
        return parentTypeArray.count;
    }
    else
        return 0;
}
- (UIView *)viewPager:(ViewPagerController *)viewPager viewForTabAtIndex:(NSUInteger)index {
    
    
    if (parentTypeArray.count>0) {
        UILabel *label = [[UILabel alloc] init];
        label.backgroundColor = [UIColor clearColor];
        label.font = [UIFont systemFontOfSize:16.0];
        
        label.text = [NSString stringWithFormat:@"%@",[parentTypeArray objectAtIndex:index]];
        
        
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor colorWithRed:102.0/255.0 green:102.0/255.0 blue:102.0/255.0 alpha:1.0];
        [label sizeToFit];
        [labelArray addObject:label];
        
        return label;
    }
    else
    {
        return  nil;
    }
}
- (UIViewController *)viewPager:(ViewPagerController *)viewPager contentViewControllerForTabAtIndex:(NSUInteger)index {
    
    for (int i=0;i<labelArray.count;i++ ) {
        UILabel *label=(UILabel *)[labelArray objectAtIndex:i];
        label.textColor=[UIColor colorWithRed:102.0/255.0 green:102.0/255.0 blue:102.0/255.0 alpha:1.0];
    }
    UILabel *label=(UILabel *)[labelArray objectAtIndex:index];
    label.textColor=[UIColor blackColor];

    
    PlaceOrderProductListViewController *cvc = [[PlaceOrderProductListViewController alloc] init];
    NSMutableArray *dataArray=[NSMutableArray arrayWithArray:[[totalDataArray objectAtIndex:index] objectForKey:@"TypeList"]];
    cvc.titleString=[parentTypeArray objectAtIndex:index];
    cvc.typeString=_Whs;
    cvc.saveTypeStr=self.Whs;
    cvc.ptype=_ptype;
    cvc.parentDataArray=[NSMutableArray arrayWithArray:dataArray];
    cvc.delegate=self;
    
    return cvc;
}

#pragma mark - ViewPagerDelegate
//- (CGFloat)viewPager:(ViewPagerController *)viewPager valueForOption:(ViewPagerOption)option withDefault:(CGFloat)value {
//
//    switch (option) {
//        case ViewPagerOptionStartFromSecondTab:
//            return 0.0;
//            break;
//        case ViewPagerOptionCenterCurrentTab:
//            return 0.0;
//            break;
//        case ViewPagerOptionTabLocation:
//            return 1.0;
//            break;
//        default:
//            break;
//    }
//
//    return value;
//}
- (UIColor *)viewPager:(ViewPagerController *)viewPager colorForComponent:(ViewPagerComponent)component withDefault:(UIColor *)color {
    
    switch (component) {
        case ViewPagerIndicator:
            return [UIColor colorWithRed:90.0/255.0 green:130.0/255.0 blue:26.0/255.0 alpha:1.0];//[[UIColor redColor] colorWithAlphaComponent:0.64];
            break;
        default:
            break;
    }
    
    return color;
}

-(void)selectedGoodsBtnClick
{
    SelectedGoodNewViewController *selectedGoodVC=[[SelectedGoodNewViewController alloc] init];//2.0{9个参数 少2个}
    
    selectedGoodVC.typeString=self.Whs;
    //    selectedGoodVC.Whs=self.Whs;
    selectedGoodVC.ckvId=self.ckvId;
    selectedGoodVC.ckvNo=self.ckvNo;
    selectedGoodVC.whsName=self.whsName;
    selectedGoodVC.itemTypeName=self.itemTypeName;
    selectedGoodVC.whsId=self.whsId;
    //    selectedGoodVC.typeString=_saveTypeStr;
    selectedGoodVC.itemTypeCode=self.itemTypeCode;
    [self.navigationController pushViewController:selectedGoodVC animated:YES];
    
}
-(void)subTableViewCellCliCK:(NSString *)itemIdString
{
    ProductDetailViewController *detailViewController = [[ProductDetailViewController alloc] init];
    detailViewController.itemIdStr=itemIdString;
    
    detailViewController.saveTypeStr=self.Whs;
    
    detailViewController.typeString=self.Whs;
    //下面继续盘点的带出来的数据
    
    
    detailViewController.ckvId=self.ckvId;
    detailViewController.ckvNo=self.ckvNo;
    detailViewController.whsName=self.whsName;
    detailViewController.itemTypeName=self.itemTypeName;
    detailViewController.whsId=self.whsId;
    detailViewController.itemTypeCode=self.itemTypeCode;
    [self.navigationController pushViewController:detailViewController animated:YES];
}
#pragma mark delegate
-(void)loginAgain
{
    TheLoginViewController *loginVC=[[TheLoginViewController alloc] init];//2.0{9个参数 少2个}
    [self.navigationController pushViewController:loginVC animated:YES];

}
-(void)confirmSubmit
{
//    NSLog(@"userToken/>>==%@",userToken);
//     NSLog(@"_whs/>>==%@",_Whs);
    NSMutableArray *productImageArray=[NSMutableArray array];
    NSMutableArray *productIDArray=[NSMutableArray array];
    NSMutableArray *productItemCodeArray=[NSMutableArray array];
//    NSMutableArray *productItemTypeArray=[NSMutableArray array];
    NSMutableArray *productNameArray=[NSMutableArray array];
    NSMutableArray *productPriceArray=[NSMutableArray array];
    NSMutableArray *productCountArray=[NSMutableArray array];
    NSMutableArray *productSpecNameArray=[NSMutableArray array];
    NSMutableArray *productSpecIDArray=[NSMutableArray array];
    NSMutableArray *productSpecPriceArray=[NSMutableArray array];
    NSMutableArray *productStockCountArray=[NSMutableArray array];
    FMResultSet *resultSet=[_userDB executeQuery:@"SELECT mainTable.itemID ,mainTable.itemCode,mainTable.itemName,mainTable.salePrice,mainTable.typeString ,mainTable.specCount AS mainCount ,mainTable.imageUrlFull , subTable.specPrice,IFNULL(subTable.specName,'') AS specName ,subTable.specCount ,subTable.specID FROM t_UserPlaceOrder mainTable LEFT JOIN t_UserSpec subTable ON mainTable.itemId = subTable.itemID AND mainTable.typeString = subTable.typeString WHERE mainTable.typeString = ? AND mainTable.userToken = ? ;",_Whs,userToken];
    while (resultSet.next) {
        NSString *itemIDString=[resultSet objectForColumnName:@"itemID"];
        NSString *itemCodeString=[resultSet objectForColumnName:@"itemCode"];
        NSString *imageUrlFullString=[resultSet objectForColumnName:@"imageUrlFull"];
        NSString *itemNameString=[resultSet objectForColumnName:@"itemName"];
        NSString *salePriceString=[resultSet objectForColumnName:@"salePrice"];
//        NSString *typeStringString=[resultSet objectForColumnName:@"typeString"];
        NSString *mainCountString=[resultSet objectForColumnName:@"mainCount"];
        
        NSString *specPriceString=[resultSet objectForColumnName:@"specPrice"];
        NSString *specNameString=[resultSet objectForColumnName:@"specName"];
        NSString *specCountString=[resultSet objectForColumnName:@"specCount"];
        NSString *specIDString=[resultSet objectForColumnName:@"specID"];
        [productIDArray addObject:itemIDString];
        [productItemCodeArray addObject:itemCodeString];
        [productImageArray addObject:imageUrlFullString];
        [productNameArray addObject:itemNameString];
        [productPriceArray addObject:salePriceString];
        [productCountArray addObject:mainCountString];
        [productSpecNameArray addObject:specNameString];
        [productSpecPriceArray addObject:specPriceString];
        [productStockCountArray addObject:specCountString];
        [productSpecIDArray addObject:specIDString];
        
        
    }
//    NSLog(@"productItemCodeArray>>>==%@",productItemCodeArray);
    
    commdity.userName=nil;
    //  shouyingViewController *shouyinVC=[[shouyingViewController alloc] init];／／1.0里面东西不管
    
    if (productItemCodeArray.count>0) {
        
        
        if ([commdity.gengxin isEqualToString:@""]) {//直接下单
            
            BusinessOrderExtAddViewController *shouyinVC=[[BusinessOrderExtAddViewController alloc] init];//2.0{9个参数 少2个}
            shouyinVC.headImageFullArray=productImageArray;
            shouyinVC.itemCodeArray=productItemCodeArray;
            
            shouyinVC.specNameArray=productSpecNameArray;
            shouyinVC.itemIdArray= productIDArray;
            shouyinVC.itemNameArray=productNameArray;
            shouyinVC.specIdArray=productSpecIDArray;
            shouyinVC.dealPriceArray=productPriceArray;
            shouyinVC.quantityArray=productCountArray;
            shouyinVC.saveTypeStr=_Whs;
            //  shouyinVC.TotalMoney=_totalLabel.text;//[NSString stringWithFormat:@"%0.02f",totalValue];
            [self.navigationController pushViewController:shouyinVC animated:YES];
            
            
        }else{
            
            //陈列入库出库盘点下单
            commdity.whsName=@"";
            commdity.content=@"";
            commdity.leixin=@"";
            commdity.code=@"";
            commdity.status=nil;
            commdity.ItemCode44= productItemCodeArray;
            commdity.Itemid44= productIDArray;
            commdity.ItemName44= productNameArray;
            commdity.ImageUrl44= productImageArray;
            commdity.Price44= productPriceArray;
            commdity.currentSpecId44=productSpecIDArray;
            commdity.how44=productCountArray;
            commdity.specName44=productSpecNameArray;
            
            
            if ([self.Whs isEqualToString:@"NeedOrder"]) {
                
                BusinessNeedOrderAddViewController *detailViewController = [[BusinessNeedOrderAddViewController alloc] init];
                detailViewController.titleName=@"确认要货";
                detailViewController.Whs=@"NeedOrder";
                 detailViewController.Type=@"NeedOrderType";
                detailViewController.saveTypeStr=self.Whs;
                [self.navigationController pushViewController:detailViewController animated:YES];
                
                
            }

            if ([self.Whs isEqualToString:@"Shelf"]) {
                
                BusinessWhsInAddViewController *detailViewController = [[BusinessWhsInAddViewController alloc] init];
                detailViewController.titleName=@"确认陈列";
                detailViewController.Whs=@"Shelf";
                detailViewController.saveTypeStr=self.Whs;
                [self.navigationController pushViewController:detailViewController animated:YES];
                
                
            }
            
            if ([self.Whs isEqualToString:@"WhsOut"]) {
                BusinessWhsInAddViewController *detailViewController = [[BusinessWhsInAddViewController alloc] init];
                detailViewController.titleName=@"确认出库";
                detailViewController.Whs=@"WhsOut";
                detailViewController.Type=@"WhsOutType";
                detailViewController.saveTypeStr=self.Whs;
                [self.navigationController pushViewController:detailViewController animated:YES];
                
                
            }
            
            if ([self.Whs isEqualToString:@"WhsIn"]) {
                BusinessWhsInAddViewController *detailViewController = [[BusinessWhsInAddViewController alloc] init];
                detailViewController.titleName=@"确认入库";
                detailViewController.Whs=@"WhsIn";
                detailViewController.Type=@"WhsInType";
                detailViewController.saveTypeStr=self.Whs;
                [self.navigationController pushViewController:detailViewController animated:YES];
                
            }
            
            
            if ([self.Whs isEqualToString:@"CheckVouch"]) {
                
                BusinessCheckVouchAddViewController *detailViewController = [[BusinessCheckVouchAddViewController alloc] init];
                detailViewController.titleName=@"确认录入";
                detailViewController.Whs=@"CheckVouch";
//                commdity.content=productItemTypeArray[0];
                commdity.content1=@"";
                detailViewController.saveTypeStr=self.Whs;
                [self.navigationController pushViewController:detailViewController animated:YES];
            }
            
            if ([self.Whs isEqualToString:@"POrder"]) {
                
                BusinessPOrderAddViewController *detailViewController = [[BusinessPOrderAddViewController alloc] init];
                detailViewController.titleName=@"采购订单";
                detailViewController.Whs=@"POrder";
                commdity.content=@"";
                detailViewController.saveTypeStr=self.Whs;
                [self.navigationController pushViewController:detailViewController animated:YES];
            }
            
            if ([self.Whs isEqualToString:@"Continue"]) {
                
                BusinessCheckVouchContinueViewController *detailViewController = [[BusinessCheckVouchContinueViewController alloc] init];
                detailViewController.titleName=@"继续盘点";
                detailViewController.Whs=@"Continue";
                detailViewController.ckvId=self.ckvId;
                detailViewController.ckvNo=self.ckvNo;
                detailViewController.whsName=self.whsName;
                detailViewController.itemTypeName=self.itemTypeName;
                detailViewController.whsId=self.whsId;
                detailViewController.itemTypeCode=self.itemTypeCode;
                detailViewController.saveTypeStr=self.Whs;
                [self.navigationController pushViewController:detailViewController animated:YES];
            }
            
        }
        
    }
    else
    {
        UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"提示" message:@"您未选择商品" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
    }
    
}

-(void)setNavigation
{
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBarHidden=NO;
    
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    
    UILabel *titleLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0,100, 21)];
    titleLabel.textAlignment=NSTextAlignmentCenter;
    titleLabel.text=@"选择商品";
    
    self.navigationItem.titleView = titleLabel;
    
    self.navigationController.navigationBar.barStyle =UIBaselineAdjustmentNone ;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    
}

-(void)BackAction
{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)scanBtnClick
{
    commdity.sat=@"SCANSHOP";
//    commdity.sat=@"SCANSHOP";
    
    
    ScanViewController*de = [[ScanViewController alloc] init];
    
    [self.navigationController pushViewController:de animated:YES];
}
//-(void)OnTapDone
//{
//    [searchTextField resignFirstResponder];
//    [self requestProductDetail:searchTextField.text];
//}
//-(BOOL)textFieldShouldReturn:(UITextField *)textField
//{
//    [searchTextField resignFirstResponder];
//    
//    [self requestProductDetail:textField.text];
//    return YES;
//    
//}
-(void)requestProductDetail:(NSString *)codeStr
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:codeStr forKey:@"itemId"];
    [Global showIndeterminateHud:@"加载中，请稍后。。。" delay:30 view:self.view];
    [HttpRequest requestData:@"Product/GetProductDetail" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        
        if (isSuccess) {
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                ProductDetailViewController *detailViewController = [[ProductDetailViewController alloc] init];
                detailViewController.itemIdStr=codeStr;
                detailViewController.itemIdStr=self.Whs;
                
                detailViewController.typeString=self.Whs;
                //下面继续盘点的带出来的数据
                //                 NSLog(@"self.Whs%@",self.Whs);
                
                detailViewController.ckvId=self.ckvId;
                detailViewController.ckvNo=self.ckvNo;
                detailViewController.whsName=self.whsName;
                detailViewController.itemTypeName=self.itemTypeName;
                detailViewController.whsId=self.whsId;
                detailViewController.itemTypeCode=self.itemTypeCode;
                
                [self.navigationController pushViewController:detailViewController animated:YES];
            }
            
            else{
                [Global hideProgressHUDInternal:self.view];
                [Global showTextHudSub:[severDataDict.dataDict objectForKey:@"ResultString"] view:self.view];
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    TheLoginViewController *loginVC=[[TheLoginViewController alloc] init];//2.0{9个参数 少2个}
                    [self.navigationController pushViewController:loginVC animated:YES];
                }

            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
        
    }];
    
}

- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}

- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}


@end
